package com.example.springbootdemo.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.example.springbootdemo.bean.core.AnyConnectionManager;
import com.example.springbootdemo.bean.core.HubConnectionManager;
import com.example.springbootdemo.bean.kernelApi.*;
import com.example.springbootdemo.dict.comparefiledict.AnalysisStatus;
import com.example.springbootdemo.dto.comparefile.ResultData;
import com.example.springbootdemo.dto.comparefile.ThingHistoryFileObj;
import com.example.springbootdemo.dto.createWorkInstance.*;
import com.example.springbootdemo.dto.project.GroupObj;
import com.example.springbootdemo.dto.project.ProjectResultObj;
import com.example.springbootdemo.response.ProjectData;
import com.example.springbootdemo.service.HistoryService;
import com.example.springbootdemo.service.KernelApiService;
import com.example.springbootdemo.utils.ReadFileUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.microsoft.signalr.HubConnection;
import com.microsoft.signalr.HubConnectionBuilder;
import lombok.extern.slf4j.Slf4j;
import lombok.var;

import org.apache.commons.text.similarity.JaccardSimilarity;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.security.auth.message.AuthException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.SignatureException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/test")
@Slf4j
public class testController {


    HubConnection hubConnection;

    @Autowired
    KernelApiService kernelApiService;

    @Autowired
    HubConnectionManager hubConnectionManager;

    @Autowired
    AnyConnectionManager anyConnectionManager;


    @Autowired
    HistoryService historyService;

    @PostMapping("/token")
    public CreateWorkInstanceRequest compareTime() throws AuthException, SignatureException {

        hubConnection = HubConnectionBuilder.create("http://orginone.cn/orginone/kernel/hub")
                .build();
        hubConnection.setKeepAliveInterval(3000);
        hubConnection.onClosed((err) -> {
            try {
                Thread.sleep(8000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            hubConnection.start().blockingAwait();
        });
        hubConnection.start().blockingAwait();

        Map<String, String> req = new HashMap<>();
        req.put("account", "18767399041");
        req.put("pwd", "Ayu*1996");
        var type = new Result<LoginData>();
        var result = hubConnection.invoke(type.getClass(),"Login", req).blockingGet();
        System.out.println(result);
        var obj = getJsonData(result,LoginData.class);
        String token = obj.getData().getAccessToken();
        System.out.println(token);


/*        CreateWorkInstanceRequest createWorkInstanceRequest = initData();
        createWorkInstanceRequest.getParams().setData(initDataJson());



        var type2 = new Result<LoginData>();
        Result request = hubConnection.invoke(type2.getClass(), "Request", createWorkInstanceRequest).blockingGet();
        System.out.println(request);*/
//        return createWorkInstanceRequest;
        return null;

    }


    //获取文件内容，比对文件
    public void compareFile(){

    }

    @RequestMapping("/createHis")
    public String createHistoryRequest(){
        CreateWorkInstanceRequest createWorkInstanceRequest = initData();

        createWorkInstanceRequest.getParams().setData(initHisDataJson());

        var type2 = new Result<LoginData>();
        Result request = hubConnectionManager.getHubConnection().invoke(type2.getClass(), "Request", createWorkInstanceRequest).blockingGet();
        System.out.println(request);
        return createWorkInstanceRequest.toString();
    }

    private String initHisDataJson(){
        ObjectMapper objectMapper = new ObjectMapper();
        RootData createWorkInstanceRequest = null;
        try {
            createWorkInstanceRequest = objectMapper.readValue(new ClassPathResource("orign.json").getFile(), RootData.class);


            //json after里面的内容
            List<DataDetail> dataDetails = new ArrayList<>();

            DataDetail dataDetail = new DataDetail();
            //主键id，设置了之后就会更新
//            dataDetail.setId("27741198015972352");
            dataDetail.setFileName("测试7");
            dataDetail.setFileContent("啊啊啊啊\n" +
                    "安安静静\n" +
                    "啊卡机卡机\n" +
                    "\n" +
                    "拉大距离五十块\n" +
                    "的理解哇撒旦记录卡\n" +
                    "\n" +
                    "1记录接口记录");
            dataDetail.setFileId("8aada46b889f5c820188aea72fdc1eba");
            dataDetail.setFilePath("/opt");
            dataDetail.setName("historyFile");
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String createTimeString = simpleDateFormat.format(date);
            dataDetail.setCreateDate(createTimeString);
            dataDetail.setStatus("正常");
            dataDetail.setReState(AnalysisStatus.SUCCESS.getCode());


            dataDetails.add(dataDetail);


/*            DataDetail dataDetail1 = new DataDetail();
            dataDetail1.setFileName("测试4");
            dataDetails.add(dataDetail1);*/


            List<DataItem> dataItems = createWorkInstanceRequest.getData().get_478992906363998208();
            DataItem dataItem = dataItems.get(0);
//            dataItem.setCreateTime(createTimeString);
            dataItem.setAfter(dataDetails);
        } catch (IOException e) {
            log.error("json转换异常");
            throw new RuntimeException(e);
        }

        String jsonString = JSONObject.toJSONString(createWorkInstanceRequest);
        return jsonString;
    }


    private <T> Result<T> getJsonData(Object obj, Class<T> clazz){
        var json = JSON.toJSONString(obj);
        var result = JSON.parseObject(json, new TypeReference<Result<T>>(clazz){});
        return result;
    }


    private  CreateWorkInstanceRequest initData() {

        ObjectMapper objectMapper = new ObjectMapper();
        CreateWorkInstanceRequest createWorkInstanceRequest = null;
        try {
            createWorkInstanceRequest = objectMapper.readValue(new ClassPathResource("work-instance.json").getFile(), CreateWorkInstanceRequest.class);
        } catch (IOException e) {
            log.error("json转换异常");
            throw new RuntimeException(e);
        }

        return createWorkInstanceRequest;

    }

    private String initDataJson(){
        ObjectMapper objectMapper = new ObjectMapper();
        RootData createWorkInstanceRequest = null;
        try {
            createWorkInstanceRequest = objectMapper.readValue(new ClassPathResource("orign.json").getFile(), RootData.class);
        } catch (IOException e) {
            log.error("json转换异常");
            throw new RuntimeException(e);
        }

        String jsonString = JSONObject.toJSONString(createWorkInstanceRequest);
        return jsonString;
    }


    @RequestMapping("/getList")
    private String getList(){

        var type = new Result<ThingHistoryFileObj>();
        var search = new ThingSearchReq();
/*        search.setSkip((1 - 1) * 10);
        search.setTake(10);*/
        search.getSort().add(new Sort("T478992412400816128", true));

        //过滤筛选
/*        LinkedList<String> strings = new LinkedList<>();
        strings.add("T478992412400816128");
        strings.add("=");
        strings.add("S478992497914286080");
        search.setFilter(strings);*/

        //通过属性筛选
        ArrayList<Object> userData = new ArrayList<>();
        userData.add("T478992412400816128");
        search.setUserData(userData);
        HubConnection anyHubConnection = anyConnectionManager.getHubConnection();
        anyConnectionManager.tokenAuthConnection();
//        hubConnection.invoke("TokenAuth", "1223244").blockingAwait();
        var  result = anyHubConnection.invoke(type.getClass(),"Load", "445723536485650432", search).blockingGet();

        var json = JSON.toJSONString(result);;
        ResultData result1 = JSON.parseObject(json, ResultData.class);
        System.out.println(result1);

        System.out.println(result1.getData().getData().size());
        return result1.toString();
    }



    public static void main(String[] args) throws IOException {
//        String filePath1 = "C:\\Users\\Administrator\\Desktop\\文件比对测试\\2.txt";
//        String filePath2 = "C:\\Users\\Administrator\\Desktop\\文件比对测试\\1.txt";

        String filePath1 = "C:\\Users\\Administrator\\Desktop\\文件比对测试\\海宁市发展和改革局-数字社会门户VPN新堡垒机服务器账号密码(1).docx";
        String filePath2 = "C:\\Users\\Administrator\\Desktop\\文件比对测试\\海宁市发展和改革局-数字社会门户VPN新堡垒机服务器账号密码(1).docx";
        File file1 = new File(filePath1);
        File file2 = new File(filePath2);

        String s2 = ReadFileUtil.readFile(file2);
        String s1 = ReadFileUtil.readFile(file1);


        JaccardSimilarity jaccardSimilarity = new JaccardSimilarity();
        Double apply = jaccardSimilarity.apply(s1, s2);
        System.out.println(apply);

    }




    @RequestMapping("/getAJNProjectList")
    public String getAJNProjectList(){
        var type = new Result<ProjectResultObj>();
        var search = new ThingManySearchReq();
        search.setSkip((1 - 1) * 10);
        search.setTake(10);
//        search.getSort().add(new Sort("T470219805513879552", true));

        //通过属性筛选
/*        ArrayList<Object> groupData = new ArrayList<>();
        GroupObj groupObj = new GroupObj();
        groupObj.setSelector("T470219805513879552");
        groupObj.setIsExpanded(false);
        groupData.add(groupObj);
        search.setGroup(groupData);*/

     /*   LinkedList<String> strings = new LinkedList<>();
        strings.add("T470219805513879552");
        strings.add("=");
        strings.add("S470218641527410688");
*/
        LinkedList<List<String>> strings = new LinkedList<>();
        ArrayList<String> filterA = new ArrayList<>();
        ArrayList<String> filterB = new ArrayList<>();
        filterA.add("T470219805513879552");
        filterA.add("=");
        filterA.add("S470218641527410688");
        strings.add(filterA);
        filterB.add("T468899332339404800");
        filterB.add("=");
        filterB.add("8aada46b889f5c820188aea72fdc1eba");
        strings.add(filterB);

        search.setFilter(strings);
        HubConnection anyHubConnection = anyConnectionManager.getHubConnection();
        anyConnectionManager.tokenAuthConnection();
//        hubConnection.invoke("TokenAuth", "1223244").blockingAwait();
        var  result = anyHubConnection.invoke(type.getClass(),"Load", "445723536485650432", search).blockingGet();
        var json = JSON.toJSONString(result);;
        ProjectResultObj result1 = JSON.parseObject(json, ProjectResultObj.class);
        System.out.println(result1);
        return result1.toString();
    }


}
